<template>
  <!-- 配件信息  编辑 新增 -->
  <div>
    <!-- 表单 -->
    <FormPanel ref="form" labelWidth="110" :cols="3" :list="formList" :isSubmitBtn="false" @formChange="formChange"></FormPanel>
    <!-- 表格 -->
    <!-- <FilterTable
      ref="table"
      columnsRef="partPartInventoryPartInventoryComponentsPartInfo"
      height="auto"
      :columns="columns"
      :dataSource="dataSource"
      :onColumnsChange="columns => (this.columns = columns)"
    ></FilterTable>-->
  </div>
</template>

<script>
import { state, mutations } from './../store';
import { dictionary } from '@/utils/dictMixin';
import { isAuthorized, sleep } from '@/utils';
import _ from 'lodash';

import { queryPartStock } from '@/api/part/partOutbound/repairMaterials/index.js';
import { getCangKuSelect } from '@/api/part/partOutbound/repairMaterials/dict.js';
import { exportExcelFile, arrayObjDeWeight } from '@/utils/index';
import { queryUnitCode } from '@/api/part/partInfo';
import { queryParyHasStorageById } from '@/api/part/partInventory/partInventory';
import { queryUsableLocations } from '@/api/part/inventoryManager/inventoryManager/index';

export default {
  name: 'cgrk_part_info',
  mixins: [dictionary],
  props: {
    partInfoRow: Object,
    type: String // 使用组件的类型 fahuodan edit jiaoyipingtai caigou
  },
  data() {
    return {
      newCK: '',
      showCK: false,
      formList: this.createList(),
      columns: this.createColumns(),
      dataSource: [],
      partStorageInfo: {} // 配件在仓库中的信息(判断库位选择是否禁用)
      // pj: false,
      // kuwei: false
    };
  },

  computed: {
    tax() {
      return state.tax;
    },
    storageType() {
      return this.formList.find(item => item.fieldName == 'STORAGE_CODE').initialValue;
    }
  },
  watch: {
    partInfoRow(partInfoRow) {
      // if (this.type == 'fahuodan' || this.type == 'edit') {
      //   this.initDataSource(partInfoRow);
      // } else this.queryPartStock(partInfoRow);
      console.log('监听执行');
      this.queryPartStock(partInfoRow);
    },
    storageType(newVal, oldVal) {
      if (newVal) {
        // this.queryPartInStorageInfo(newVal);
        this.queryLocationByPartAndStorage();
      }
    }
  },
  mounted() {
    window.cgrk_part_info = this;
    this.queryUnitCode();
    console.log(state, '公共参数');
    this.querySorageByType();
    this.formList.find(x => x.fieldName == 'PART_TYPE').itemList = this.createDictList('5000');
    // 权限管控(去除该判断，由于入库逻辑修改仓库库位现在本页面固定不可修改 hxj 2020-1-2)
    // this.handleQx();

    // 编辑时禁用仓库库位配件名称
    if (this.type == 'edit') {
      this.initEditFormDisabled();
    }
  },
  methods: {
    handleQx() {
      this.formList.find(x => x.fieldName == 'STORAGE_CODE').disabled = !isAuthorized('1313', '13131013');
    },
    async queryUnitCode() {
      const res3 = await queryUnitCode();
      let data = arrayObjDeWeight(res3.data, 'UNIT_CODE');
      this.columns.find(item => item.dataIndex == 'UNIT_CODE').editItems = data.map(x => ({ text: x.UNIT_NAME, value: x.UNIT_CODE }));
    },
    // 查询配件信息  通过双击配件搜索列表传来的参数
    async queryPartStock(row) {
      console.log('查询执行');
      if (!row.STORAGE_CODE) {
        this.initDataSource();
      } else {
        try {
          const res = await queryPartStock({
            partNo: row['PART_NO'],
            storageCode: row['STORAGE_CODE']
          });
          if (res.resultCode == 200) {
            this.initDataSource(res.data.rows[0]);
          }
        } catch (err) {
          console.log('查询配件 失败', err);
        }
      }
    },
    // 初始化数据 父页面调用 这个 partInfo 是整合之后的
    // partInfo看着是查询回来的下方数据 修改为一直查询
    initDataSource(partInfo) {
      console.log('初始化执行');
      const partInfoRow = this.partInfoRow;
      this.newCK = partInfoRow['STORAGE_CODE'];
      // 显示的：IN_QUANTITY入库数量   IN_PRICE入库不含税单价  IN_AMOUNT入库不含税金额  IN_PRICE_TAXED入库含税单价  IN_AMOUNT_TAXED入库含税金额
      if (this.type == 'add') {
        // 更新条件
        this.showCK = false;
        this.formList.find(x => x.fieldName === 'STORAGE_CODE').initialValue = partInfoRow['STORAGE_CODE'];
        this.formList.find(x => x.fieldName === 'PART_NO').initialValue = partInfoRow['PART_NO'];
        this.formList.find(x => x.fieldName === 'PART_NAME').initialValue = partInfoRow['PART_NAME'];
        this.formList.find(x => x.fieldName === 'PART_TYPE').initialValue = partInfoRow['PART_TYPE'];
        this.formList.find(x => x.fieldName === 'IN_QUANTITY').initialValue = partInfoRow['IN_QUANTITY'];
        this.formList.find(x => x.fieldName === 'IN_PRICE').initialValue = partInfoRow['COST_PRICE'];
        this.formList.find(x => x.fieldName === 'IN_QUANTITY').initialValue = 1;
      } else {
        // this.type == 'jiaoyipingtai' || this.type == 'caigou' || this.type == 'fahuodan' this.type == 'edit' 以前走这个 改成循环
        this.formList.map(item => {
          if (item.fieldName == 'IN_PRICE') {
            item.initialValue = partInfoRow.IN_PRICE || partInfoRow.COST_PRICE;
          } else {
            item.initialValue = partInfoRow[item.fieldName];
          }
        });
        // 是否勾选输入不含税价单独控制
        this.formList.find(item => item.fieldName == 'ifTaxed').initialValue = 1;
      }

      // this.formList = [...this.formList];
      this.dataSource = JSON.parse(JSON.stringify([partInfo || []]));
      this.computP1();
    },
    createList() {
      return [
        {
          type: 'SELECT',
          label: '仓库',
          fieldName: 'STORAGE_CODE',
          itemList: state.dict_ck,
          disabled: true,
          hidden: this.type == 'add' ? true : false,
          // rules: [{ required: true, message: '请选择仓库', trigger: 'change' }],
          change: val => {
            if (this.newCK == val) {
              this.showCK = false;
            } else {
              this.showCK = true;
            }
          }
        },
        {
          type: 'SELECT',
          label: '配件类别',
          // sorter: true,
          fieldName: 'PART_TYPE',
          disabled: true,
          itemList: [],
          hidden: this.type == 'add' ? true : false
        },
        {
          type: 'SELECT',
          label: '库位',
          fieldName: 'STORAGE_POSITION_CODE',
          disabled: true,
          hidden: this.type == 'add' ? true : false,
          itemList: []
          // rules: [{ required: true, message: '请选择库位库位', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'PART_NO',
          disabled: true,
          hidden: this.type == 'add' ? true : false,
          rules: [{ required: true, message: '请输入配件代码', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '配件名称',
          disabled: true,
          fieldName: 'PART_NAME',
          hidden: this.type == 'add' ? true : false,
          rules: [{ required: true, message: '请输入配件名称', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '入库数量', // 填写的
          fieldName: 'IN_QUANTITY',
          hidden: this.type == 'add' ? true : false,
          rules: [
            { required: true, message: '请输入入库数量', trigger: 'change' },
            { pattern: /[\d\.]+/g, message: '只允许输入入库数量' }
          ],
          change: val => {
            console.log(val, '入库数量改变');
            this.formList.find(x => x.fieldName === 'IN_QUANTITY').initialValue = val;
            this.computP1();
            console.log(this.partInfoRow, 'this.partInfoRow的数据');
            if (this.type == 'jiaoyipingtai' || this.type == 'caigou' || this.type == 'fahuodan') {
              if (Number(val) > Number(this.partInfoRow.IN_QUANTITY_MAX)) {
                this.$notify({
                  title: '警告',
                  message: '配件入库数量不允许大于单据中的数量',
                  type: 'warning'
                });
                return;
              }
            }
          }
        },
        {
          type: 'INPUT_NUMBER',
          label: '入库不含税单价', // 填写的
          fieldName: 'IN_PRICE',
          hidden: true,
          rules: [{ required: true, message: '请输入入库不含税单价', trigger: 'change' }],
          change: val => {
            console.log('入库不含税单价 change');
            this.formList.find(x => x.fieldName === 'IN_PRICE').initialValue = val;
            this.computP1();
          },
          disabled: false
        },
        {
          type: 'INPUT_NUMBER',
          label: '入库不含税金额', // 填写的
          fieldName: 'IN_AMOUNT',
          hidden: true,
          disabled: true,
          rules: [{ required: true, message: '请输入入库不含税金额', trigger: 'change' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '入库含税单价', // 填写的
          fieldName: 'IN_PRICE_TAXED',
          hidden: this.type == 'add' ? true : false,
          disabled: false,
          precision: 2,
          rules: [{ required: true, message: '请输入入库含税单价', trigger: 'change' }],
          change: val => {
            console.log('入库含税单价 change');
            this.formList.find(x => x.fieldName === 'IN_PRICE_TAXED').initialValue = val;
            this.computP2();
          }
        },
        {
          type: 'INPUT_NUMBER',
          label: '入库含税金额', // 填写的
          fieldName: 'IN_AMOUNT_TAXED',
          hidden: this.type == 'add' ? true : false,
          disabled: true
        },
        {
          type: 'CHECKBOX',
          label: '输入不含税价', // 填写的
          fieldName: 'ifTaxed',
          hidden: true,
          initialValue: 1,
          options: { trueValue: 1, falseValue: 0 },
          change: val => {
            console.log('输入不含税价 change', val);
            this.formList.find(x => x.fieldName === 'IN_PRICE').disabled = !!!val;
            this.formList.find(x => x.fieldName === 'IN_PRICE_TAXED').disabled = !!val;
          }
        }
      ];
    },
    createColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 100,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '销售价',
          sorter: true,
          dataIndex: 'SALES_PRICE',
          filter: true,
          filterType: 'number'
        },
        {
          title: '索赔价',
          sorter: true,
          dataIndex: 'CLAIM_PRICE',
          hidden: !isAuthorized('1313', '13131006'),
          filter: true,
          filterType: 'number'
        },
        {
          title: '终端建议零售价格',
          sorter: true,
          dataIndex: 'INSURANCE_PRICE',
          filter: true,
          filterType: 'number'
        },
        {
          title: '最低销售限价',
          sorter: true,
          dataIndex: 'MIN_LIMIT_PRICE',
          filter: true,
          filterType: 'number'
        },
        {
          title: '销售限价',
          sorter: true,
          dataIndex: 'LIMIT_PRICE',
          filter: true,
          filterType: 'number'
        },
        {
          title: '建议销售价',
          sorter: true,
          dataIndex: 'INSTRUCT_PRICE',
          filter: true,
          filterType: 'number'
        },
        {
          title: '最大库存',
          sorter: true,
          dataIndex: 'MAX_STOCK',
          filter: true,
          filterType: 'number'
        },
        {
          title: '最小库存',
          sorter: true,
          dataIndex: 'MIN_STOCK',
          filter: true,
          filterType: 'number'
        },
        {
          title: '账面库存',
          sorter: true,
          dataIndex: 'STOCK_QUANTITY',
          filter: true,
          filterType: 'number'
        },
        {
          title: '可用库存',
          sorter: true,
          dataIndex: 'USEABLE_STOCK',
          filter: true,
          filterType: 'number'
        },
        // {
        //   title: '借进数量',
        //   // sorter: true,
        //   dataIndex: 'BORROW_QUANTITY'
        // },
        // {
        //   title: '借出数量',
        //   // sorter: true,
        //   dataIndex: 'LEND_QUANTITY'
        // },
        {
          title: '锁定量',
          sorter: true,
          dataIndex: 'LOCKED_QUANTITY',
          filter: true,
          filterType: 'number'
        },
        {
          title: '替代配件',
          // sorter: true,
          dataIndex: 'OPTION_NO',
          filter: true,
          filterType: 'input'
        },
        {
          title: '替代件库存',
          sorter: true,
          dataIndex: 'OPTION_STOCK',
          filter: true,
          filterType: 'number'
        },
        {
          title: '配件类别',
          // sorter: true,
          dataIndex: 'PART_GROUP_CODE',
          render: props => {
            return <span>{this.createDictText(props.row.PART_GROUP_CODE, '8247')}</span>;
          },
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(8247)
        },
        {
          title: '计量单位',
          // sorter: true,
          dataIndex: 'UNIT_CODE',
          filter: true,
          filterType: 'input',
          disabled: true,
          editable: true,
          editType: 'select',
          editItems: []
        }
      ];
    },
    // 收集表达数据 Add页面触发
    async formChange(val, isEdit) {
      console.log('formChange', val);
      const row = Object.assign({}, this.dataSource[0] || {}, this.partInfoRow || {}, { $index_edit: this.partInfoRow.$index_edit }, val);
      console.log(row, 'row::');
      // 判断 仓库是否已选
      // if (row.STORAGE_CODE === null || row.STORAGE_CODE === '') {
      //   this.$notify({
      //     title: '警告',
      //     message: '仓库未选择',
      //     type: 'warning'
      //   });
      //   return;
      // }
      // 判断 配件是否已选
      if (!row['PART_NO']) {
        this.$notify({
          title: '警告',
          message: '未选择配件',
          type: 'warning'
        });
        return;
      }
      if (Number(row['IN_QUANTITY']) < 0.01) {
        this.$notify({
          title: '警告',
          message: '数量不能小于0.01',
          type: 'warning'
        });
        return;
      }
      if (this.type == 'jiaoyipingtai' || this.type == 'caigou' || this.type == 'fahuodan') {
        // 判断 数量是否大于最大库存
        if (Number(row.IN_QUANTITY) > Number(row.IN_QUANTITY_MAX)) {
          this.$notify({
            title: '警告',
            message: '配件入库数量不允许大于单据中的数量',
            type: 'warning'
          });
          return;
        }
      }
      state.dict_ck.forEach(x => {
        if (x.value === row.STORAGE_CODE) {
          row.STORAGE_NAME = x.text;
        }
      });
      if (this.type == 'add') {
        this.$emit('partSearthSuccess', row);
      }
      if (isEdit) {
        this.$emit('getEditPartInfo', row);
      }
    },
    // 计算价格
    async computP1() {
      try {
        let sl = Number(state.tax);
        console.log('税率', sl);
        // 数量
        let IN_QUANTITY = this.formList.find(x => x.fieldName === 'IN_QUANTITY').initialValue || 1;
        // 入库 不含税单价
        let IN_PRICE = (Number(this.formList.find(x => x.fieldName === 'IN_PRICE').initialValue) || 0).toFixed(2);
        // 入库含税单价
        let IN_PRICE_TAXED = _.isNil(this.partInfoRow.IN_PRICE_TAXED) ? (Number(IN_PRICE) * (sl + 1)).toFixed(2) : this.partInfoRow.IN_PRICE_TAXED;
        this.formList.find(x => x.fieldName === 'IN_PRICE_TAXED').initialValue = IN_PRICE_TAXED;
        // 入库不含税金额
        let IN_AMOUNT = (Number(IN_QUANTITY) * Number(IN_PRICE)).toFixed(2);
        this.formList.find(x => x.fieldName === 'IN_AMOUNT').initialValue = IN_AMOUNT;
        // 入库含税金额
        let IN_AMOUNT_TAXED = (Number(IN_QUANTITY) * Number(IN_PRICE_TAXED)).toFixed(2);
        this.formList.find(x => x.fieldName === 'IN_AMOUNT_TAXED').initialValue = IN_AMOUNT_TAXED;
        this.formList.find(x => x.fieldName === 'IN_QUANTITY').initialValue = Number(IN_QUANTITY).toFixed(2);
        this.formList.find(x => x.fieldName === 'IN_PRICE').initialValue = Number(IN_PRICE).toFixed(2);
      } catch (err) {
        console.err(err);
      }

      await sleep(20);
      let formdata = await this.$refs.form.GET_FORM_DATA();
      if (formdata[1]) {
        this.formChange(formdata[1]);
      }
    },
    computP2() {
      let sl = Number(state.tax);
      this.formList = [...this.formList];
      // 数量
      let IN_QUANTITY = this.formList.find(x => x.fieldName === 'IN_QUANTITY').initialValue || 1;
      // 入库 含税单价
      let IN_PRICE_TAXED = (Number(this.formList.find(x => x.fieldName === 'IN_PRICE_TAXED').initialValue) || 0).toFixed(2);
      // 入库 不含税单价
      let IN_PRICE = (Number(IN_PRICE_TAXED) / (sl + 1)).toFixed(2);
      this.formList.find(x => x.fieldName === 'IN_PRICE').initialValue = IN_PRICE;
      // 入库 不含税金额
      let IN_AMOUNT = (Number(IN_QUANTITY) * Number(IN_PRICE)).toFixed(2);
      this.formList.find(x => x.fieldName === 'IN_AMOUNT').initialValue = IN_AMOUNT;
      // 入库含税金额
      let IN_AMOUNT_TAXED = (Number(IN_QUANTITY) * Number(IN_PRICE_TAXED)).toFixed(2);
      this.formList.find(x => x.fieldName === 'IN_AMOUNT_TAXED').initialValue = IN_AMOUNT_TAXED;
      this.formList.find(x => x.fieldName === 'IN_PRICE_TAXED').initialValue = Number(IN_PRICE_TAXED).toFixed(2);
    },
    // 根据类型查询仓库(发货单交易平台只能查询到oem库，采购和手工入库只能是非oem 其余不限制查所有)
    async querySorageByType() {
      let res = await getCangKuSelect({
        type: this.type == 'fahuodan' || this.type == 'jiaoyipingtai' ? 1 : this.type == 'caigou' || this.type == 'add' ? 0 : '' // 0是非oem 1是oem
      });
      this.formList.find(item => item.fieldName == 'STORAGE_CODE').itemList = res.data.map(item => ({ text: item.STORAGE_NAME, value: item.STORAGE_CODE }));
    },
    // 根据仓库及配件代码查询库位(列表数据)
    async queryLocationByPartAndStorage() {
      let partNo = this.formList.find(item => item.fieldName == 'PART_NO').initialValue;
      let res = await queryUsableLocations({
        storageCode: this.storageType,
        partNo
      });
      this.formList.find(item => item.fieldName == 'STORAGE_POSITION_CODE').itemList = res.data.map(item => ({ text: item.storagePositionCode, value: item.storagePositionCode }));
    },
    // 根据仓库及配件代码查询是否有库位
    async queryPartInStorageInfo(storageCode) {
      let partNo = this.formList.find(item => item.fieldName == 'PART_NO').initialValue;
      let res = await queryParyHasStorageById({
        storageCode,
        partNo
      });
      if (res.resultCode == 200) {
        let formTarget = this.formList.find(item => item.fieldName == 'STORAGE_POSITION_CODE');
        // formTarget.disabled = !!(res.data.length && res.data[0].storagePositionCode);
        formTarget.initialValue = res.data[0] ? res.data[0].storagePositionCode : '';
      }
    },
    // 编辑初始化表单禁用
    initEditFormDisabled() {
      let disabledList = ['STORAGE_CODE', 'STORAGE_POSITION_CODE', 'PART_NAME'];
      disabledList.map(item => {
        this.formList.find(item2 => item2.fieldName == item).disabled = true;
      });
    },
    // 编辑点击确定(hack处理原逻辑过于复杂且用法错误无法修改)
    async handleEditConfirm() {
      let formData = await this.$refs.form.GET_FORM_DATA();
      if (formData[1]) {
        this.formChange(formData[1], true);
      }
    }
  }
};
</script>

<style></style>
